<?php
/**
 * Created by PhpStorm.
 * User: tsy
 * Date: 2016/11/1
 * Time: 14:42
 */
namespace Admin\Controller\Common;
use Think\Controller;

class AnRongApiController extends Controller{
    function personIdCard_for_Impl($cust_name,$cust_identity,$cust_id,$cust_phone){
        $url=C("ar_url");
        $member=C("ar_member");
        $key=C("ar_key");

        $sign=strtoupper(md5($cust_name.$cust_identity.$member.$key));
        $custname=urlencode($cust_name);
        $url=$url."?name=$custname&cid=$cust_identity&member=$member&sign=$sign";
        $result=curl_page_exec($url);
        $ar_api=A("Admin/Common/AnRongApi");
        $resultV=$ar_api->result_validate($result, $cust_identity, $cust_id, 1,$cust_name);
        if($resultV==1&&$cust_phone!=''){

            $sendMessage=new \Admin\Controller\Common\SendMessageController();
            $array=array(
                "0"=>array("custName","**".substr($cust_name,-1)),
                "1"=>array("custIdentity","**************".substr($cust_identity,-4))
            );
            $message=$sendMessage->short_message_context("0002",$array);
            $sendMessage->sendSMS("",$cust_phone,$message);
        }
        return $resultV;
    }

    public function result_validate($result,$card,$custid,$type,$cust_name){

        if($result==null||$result==''){
            return 4;//没有数据
        }
        $ar_api=A("Admin/Common/AnRongApi");
        $anrongList=$ar_api->anrongList();
        $result_json=json_decode($result);
        $message=$result_json->message;
        $result_anRong=$result_json->result;
        $name=$result_json->name;
        $message_content=$anrongList[$message];

        $data['cust_name']=$cust_name;
        $data['number']=$card;
        $data['message_number']=$message;
        $data['message']=$message_content;
        $data['result']=$result_anRong;
        $data['cust_id']=$custid;
        $data['type']=$type;
        $data['validate_time']=date('Y-m-d H:i:s',time());

        $validate_model=D("bypal_impl_validate");
        $validate_model->save();
        if($message=='0000'){
            if($result_anRong=='1'){
                return 1;//验证成功
            }else{
                return 2;//验证失败
            }
        }else{
            return 3;//接口调用失败
        }
    }

    function anrongList(){
        return $anrongList = array(
            "0000" => "提交成功",
            "0001" => "必填参数不能为空！",
            "0001_wrong" => "必填参数格式错误",
            "0002" => "授权失败",
            "0003_sfrz" => "身份认证查询接口欠费",
            "0003_grgs" => "个人工商查询接口欠费",
            "0003_ylkyz" => "银联卡验证接口欠费",
            "0003_grzdduoka" => "个人账单 多卡查询接口欠费",
            "0003_grzddanka" => "个人账单 单卡查询接口欠费",
            "0003_shzdduoka" => "商户账单 多卡查询接口欠费",
            "0003_shzddanka" => "商户账单 单卡查询接口欠费",
            "0003_grbg" => "个人报告查询接口欠费",
            "0003_more_grbg" => "个人报告多卡查询接口欠费",
            "0003_shbg" => "商户报告查询接口欠费",
            "0003_more_shbg" => "商户报告多mid(商户编号)查询接口欠费",
            "0004" => "系统错误",
            "0005_card" => "个人报告和个人账单多卡查询接口传入的card的银行卡号数量不能大于五个",
            "0005_onlyonecard" => "个人报告和个人账单单卡查询接口传入的card的银行卡号数量只能为一个",
            "0005_mid" => "商户报告和商户账单多mid查询接口传入的mid的商户编号数量不能大于五个",
            "0005_onlyonemid" => "商户报告和商户账单单mid查询接口传入的mid的商户编号数量只能为一个",
            "0005_less2" => "银联卡账单多卡查询接口传入的银联卡数不能小于2张",
            "0005_cardfail" => "银联卡验证失败，不出账单",
            "0006" => "未查到相关数据，此笔查询不扣费"
        );
    }

    /**
     * 贷款申请
     * @param unknown $customerName 借款人姓名
     * @param unknown $paperNumber 身份证号码
     * @param unknown $applyId	申请编号(唯一)
     * @param unknown $loanType 申请贷款类型
     * @param unknown $loanMoney 申请贷款金额
     * @param unknown $currency 币种
     * @param unknown $loanTimeLimit 贷款期限(以月为单位)
     * @param unknown $assureType 担保方式
     * @param unknown $applyDate 申请日期
     * @param unknown $creditAddress 借款地点中文描述,如:北京市
     */
    function createApply($customerName,$paperNumber,$applyId,$loanType,$loanMoney,$currency,$loanTimeLimit,$assureType,$applyDate,$creditAddress){
        $data=C("ar_credit_login")."&method=createApply&customerName=$customerName&paperNumber=$paperNumber&".
            "applyId=$applyId&loanType=$loanType&loanMoney=$loanMoney&currency=$currency&loanTimeLimit".
            "=$loanTimeLimit&assureType=$assureType&applyDate=$applyDate&creditAddress=$creditAddress&certain=1";
        $result= curl_grab_page(C("ar_credit_url"),C("ar_credit_ref_url") ,$data, "true",  "null", "false");
// 		echo $result;
//        $dir=date('Ymd',time());
//        $path=dirname(dirname(__FILE__))."/logs/".$dir.".log";
//        $file=fopen($path,"a+");
        $date=date('Y-m-d H:i:s',time());
//
//        fwrite($file,"\xEF\xBB\xBF[".$date."]安融接口调用：分期ID".$applyId." \r\n");
//        fwrite($file,"\xEF\xBB\xBF[".$date."]安融接口调用：返回结果".$result." \r\n");
        \Think\Log::write("\xEF\xBB\xBF[".$date."]安融接口调用：分期ID".$applyId,'WARN');
        \Think\Log::write("\xEF\xBB\xBF[".$date."]安融接口调用：返回结果".$result,'WARN');
        $ar_api=A("Admin/Common/AnRongApi");
        $anrongList=$ar_api->curl_for_sql($result,$paperNumber);
        return $anrongList;
    }

    /**
     * 提交贷款审批结果
     * @param unknown $applyId 申请编号(唯一)
     * @param unknown $applyResult 审批结果
     * @param unknown $applyResultTime 审批日期
     * @param unknown $paperNumber 身份证号码
     */
    function checkApply($applyId,$applyResult,$applyResultTime,$paperNumber){
        $data=C("ar_credit_login")."&method=checkApply&applyId=$applyId&applyResult=$applyResult&applyResultTime=$applyResultTime";
        $result=curl_grab_page(C("ar_credit_url"),C("ar_credit_ref_url") , $data, "true",  "null", "false");
// 		$this->curl_for_sql($result,$paperNumber);
    }

    function curl_for_sql($result,$paperNumber){
//        $rvlue = 0;
        if($result==''||$result==null){
            $rvlue['state']=2;
            $rvlue['message']="没有数据";
            return $rvlue;
        }
        $createApply=strstr($result, "{");
        $obj=json_decode($createApply);
        $error=$obj->{'errors'};
        if($error!=null){
            $errorCode=$error[0]->errorCode;
            $msg=$error[0]->msg;
//            $rvlue = 1;
            $rvlue['state']=2;
            $rvlue['message']=$msg;
            return $rvlue;
        }
        $an_rong=D("AnRong");
        $abnormalCreditDetails= $obj->{'abnormalCreditDetails'};
        if($abnormalCreditDetails!=null){
            $an_rong->delete_anrong_creditdetail($paperNumber);
            $abnormalCreditDetail_model=M("bypal_impl_abnormalcreditdetail");
            $impl_overdues=M("bypal_impl_overdues");
            foreach($abnormalCreditDetails as $abnormalCreditDetail){
                $annormal_data['assureType']=$abnormalCreditDetail->assureType;
                $annormal_data['creditEndDate']=$abnormalCreditDetail->creditEndDate;
                $annormal_data['creditStartDate']=$abnormalCreditDetail->creditStartDate;
                $annormal_data['loanMoney']=$abnormalCreditDetail->loanMoney;
                $annormal_data['loanPeriods']=$abnormalCreditDetail->loanPeriods;
                $annormal_data['loanType']=$abnormalCreditDetail->loanType;
                $annormal_data['paperNumber']=$paperNumber;
                $overdues=$abnormalCreditDetail->overdues;


                $abnormalCreditDetailId=$abnormalCreditDetail_model->add($annormal_data);

                foreach ($overdues as $overdue){
                    $overdues_data['checkOverdueDate']=$overdue->checkOverdueDate;
                    $overdues_data['operTime']=$overdue->operTime;
                    $overdues_data['overdueDays']=$overdue->overdueDays;
                    $overdues_data['overdueReason']=$overdue->overdueReason;
                    $overdues_data['overdueState']=$overdue->overdueState;
                    $overdues_data['remark']=$overdue->remark;
                    $overdues_data['abnc_id']=$abnormalCreditDetailId;

                    $impl_overdues->add($overdues_data);
//                    $overdue_sql="insert into bypal_impl_overdues(abnc_id,checkOverdueDate,operTime".
//                        ",overdueDays,overdueReason,overdueState,remark) values('$abnormalCreditDetailId',".
//                        "'$checkOverdueDate','$operTime','$overdueDays','$overdueReason','$overdueState','$remark')";
//                    $dbObject->execute_dml($overdue_sql);
                }
            }
        }
        $applyDetails= $obj->{'applyDetails'};
        if($applyDetails!=null){
            $applyDetails_model=M("bypal_impl_applydetails");
            $an_rong->delete_apply_details($paperNumber);
//            $applyDetail_sql="insert into bypal_impl_applyDetails(applyDate,memberType,creditAddress,".
//                "loanType,loanMoney,applyResult,remark,paperNumber) values";
            $applyDetails_array=array();
            $i=0;
            foreach ($applyDetails as $applyDetail){
                $applyDetails_array[$i]['applyDate']=$applyDetail->applyDate;
                $applyDetails_array[$i]['applyResult']=$applyDetail->applyResult;
                $applyDetails_array[$i]['creditAddress'] =$applyDetail->creditAddress;
                $applyDetails_array[$i]['loanMoney'] =$applyDetail->loanMoney;
                $applyDetails_array[$i]['loanType'] =$applyDetail->loanType;
                $applyDetails_array[$i]['memberType'] =$applyDetail->memberType;
                $applyDetails_array[$i]['remark'] =$applyDetail->remark;
                $applyDetails_array[$i]['paperNumber'] =$paperNumber;
                $i++;
//                $applyDetail_sql=$applyDetail_sql."('$applyDate','$memberType','$creditAddress'".
//                    ",'$loanType','$loanMoney','$applyResult','$remark','$paperNumber'),";
            }
//            $applyDetail_sql = substr($applyDetail_sql,0,strlen($applyDetail_sql)-1);
//            $dbObject->execute_dml($applyDetail_sql);
            if($i>0) {
                $applyDetails_model->addAll($applyDetails_array);
            }
        }
        $blackDatas= $obj->{'blackDatas'};
        if($blackDatas!=null){
//            $delete_sql="delete from bypal_impl_blackData where paperNumber=$paperNumber";
//            $dbObject->execute_dml($delete_sql);
            $an_rong->delete_black_data($paperNumber);
            $blackData_model=M("bypal_impl_blackData");
            $blackData_array=array();
//            $blackData_sql="insert into bypal_impl_blackData(createDate,creditAddress,arrears,overdueDays".
//                ",phone,email,residenceAddress,currentAddress,paperNumber) values";
            $i=0;
            foreach ($blackDatas as $blackData){
                $blackData_array[$i]['createDate']=$blackData->createDate;
                $blackData_array[$i]['creditAddress'] =$blackData->creditAddress;
                $blackData_array[$i]['arrears'] =$blackData->arrears;
                $blackData_array[$i]['overdueDays'] =$blackData->overdueDays;
                $blackData_array[$i]['phone'] =$blackData->phone;
                $blackData_array[$i]['email'] =$blackData->email;
                $blackData_array[$i]['residenceAddress'] =$blackData->residenceAddress;
                $blackData_array[$i]['currentAddress'] =$blackData->currentAddress;
                $blackData_array[$i]['paperNumber'] =$paperNumber;
                $i++;
//                $blackData_sql=$blackData_sql."('$createDate','$creditAddress','$arrears',".
//                    "'$overdueDays','$phone','$email','$residenceAddress','$currentAddress',".
//                    "'$paperNumber'),";
            }
//            $blackData_sql = substr($blackData_sql,0,strlen($blackData_sql)-1);
//            $dbObject->execute_dml($blackData_sql);
            if($i>0) {
                $blackData_model->addAll($blackData_array);
            }
        }
        $normalCreditDetails= $obj->{'normalCreditDetails'};
        if($normalCreditDetails!=null){
//            $delete_sql="delete from bypal_impl_normalCreditDetail where paperNumber=$paperNumber";
//            $dbObject->execute_dml($delete_sql);
            $an_rong->delete_normalCreditDetail($paperNumber);
            $normalCreditDetail_model=M("bypal_impl_normalcreditdetail");
            $normalCreditDetail_array=array();
//            $normalCreditDetail_sql="insert into bypal_impl_normalCreditDetail(creditStartDate,creditEndDate".
//                ",creditAddress,loanType,assureType,loanMoney,loanPeriods,remark,paperNumber) values";
            $i=0;
            foreach ($normalCreditDetails as $normalCreditDetail){
                $normalCreditDetail_array[$i]['assureType']=$normalCreditDetail-> assureType;
                $normalCreditDetail_array[$i]['creditAddress']=$normalCreditDetail-> creditAddress;
                $normalCreditDetail_array[$i]['creditEndDate']=$normalCreditDetail-> creditEndDate;
                $normalCreditDetail_array[$i]['creditStartDate']=$normalCreditDetail-> creditStartDate;
                $normalCreditDetail_array[$i]['loanMoney']=$normalCreditDetail-> loanMoney;
                $normalCreditDetail_array[$i]['loanPeriods']=$normalCreditDetail-> loanPeriods;
                $normalCreditDetail_array[$i]['loanType']=$normalCreditDetail-> loanType;
                $normalCreditDetail_array[$i]['remark']=$normalCreditDetail-> remark;
                $normalCreditDetail_array[$i]['paperNumber']=$paperNumber;
                $i++;
//                $normalCreditDetail_sql=$normalCreditDetail_sql."('$creditStartDate',".
//                    "'$creditEndDate','$creditAddress','$loanType','$assureType','$loanMoney','$loanPeriods'".
//                    ",'$remark','$paperNumber'),";
            }
            if($i>0) {
                $normalCreditDetail_model->addAll($normalCreditDetail_array);
            }
//            $normalCreditDetail_sql = substr($normalCreditDetail_sql,0,strlen($normalCreditDetail_sql)-1);
//            $dbObject->execute_dml($normalCreditDetail_sql);
        }
        $queryDetails= $obj->{'queryDetails'};
        if($queryDetails!=null){
//            $delete_sql="delete from bypal_impl_queryDetail where paperNumber=$paperNumber";
//            $dbObject->execute_dml($delete_sql);
            $an_rong->delete_queryDetail($paperNumber);
            $queryDetail_model=M("bypal_impl_querydetail");
            $queryDetail_array=array();
            $i=0;
//            $queryDetail_sql="insert into bypal_impl_queryDetail(queryDate,memberType,queryType,".
//                "remark,paperNumber) values";
            foreach ($queryDetails as $queryDetail){
                $queryDetail_array[$i]['memberType']=$queryDetail-> memberType;
                $queryDetail_array[$i]['queryDate']=$queryDetail-> queryDate;
                $queryDetail_array[$i]['queryType']=$queryDetail-> queryType;
                $queryDetail_array[$i]['remark']=$queryDetail-> remark;
                $queryDetail_array[$i]['paperNumber']=$paperNumber;
//                $queryDetail_sql=$queryDetail_sql."('$queryDate','$memberType','$queryType',".
//                    "'$remark','$paperNumber'),";
                $i++;
            }
            if($i>0) {
                $queryDetail_model->addAll($queryDetail_array);
            }
//            $queryDetail_sql = substr($queryDetail_sql,0,strlen($queryDetail_sql)-1);
//            $dbObject->execute_dml($queryDetail_sql);
        }
        $titles= $obj->{'title'};
        if($titles!=null){
//            $delete_sql="delete from bypal_impl_title where paperNumber=$paperNumber";
//            $dbObject->execute_dml($delete_sql);
            $title_model=M("bypal_impl_title");
            $title_array=array();
            $an_rong->delete_title($paperNumber);
            $title_array['applyPassedCount']=$titles-> applyPassedCount;
            $title_array['applyRejectCount']=$titles-> applyRejectCount;
            $title_array['applyTotalCount']=$titles-> applyTotalCount;
            $title_array['applyingCount']=$titles-> applyingCount;
            $title_array['customerName']=$titles-> customerName;
            $title_array['ejqCount']=$titles-> ejqCount;
            $title_array['etotalCount']=$titles-> etotalCount;
            $title_array['ewjqCount']=$titles-> ewjqCount;
            $title_array['jqCount']=$titles-> jqCount;
            $title_array['paperNumber']=$titles-> paperNumber;
            $title_array['queryCount']=$titles-> queryCount;
            $title_array['queryNumber']=$titles-> queryNumber;
            $title_array['reportTime']=$titles-> reportTime;
            $title_array['totalCount']=$titles-> totalCount;
            $title_array['wjqCount']=$titles-> wjqCount;
            $title_model->add($title_array);
//            $title_sql="insert into bypal_impl_title(applyPassedCount,applyRejectCount,applyTotalCount".
//                ",applyingCount,customerName,ejqCount,ewjqCount,etotalCount,jqCount,wjqCount,totalCount,".
//                "paperNumber,queryCount,queryNumber,reportTime) values('$applyPassedCount',".
//                "'$applyRejectCount','$applyTotalCount','$applyingCount','$customerName','$ejqCount',".
//                "'$ewjqCount','$etotalCount','$jqCount','$wjqCount','$totalCount','$paperNumber',".
//                "'$queryCount','$queryNumber','$reportTime')";
//            $dbObject->execute_dml($title_sql);
        }
//        $rvlue = 2;
        $rvlue['state']=1;
        $rvlue['message']="安融操作成功";
        return $rvlue;
    }
}